﻿using System;
using System.Globalization;
using System.Web;

namespace Honeycomb.Core
{
    /// <summary>
    /// Grid URI implementation.
    /// </summary>
    public class GridUri : Uri
    {
        public const int DefaultPort = 7271;

        /// <summary>
        /// Constuctor, parses a grid URI.
        /// </summary>
        /// <param name="uri">URI String.</param>
        public GridUri(string uri) : base(uri)
        {
            if (string.Compare(Scheme, "grid", true, CultureInfo.InvariantCulture) != 0)
                throw new ArgumentException("Grid URI:s must use the grid:// naming scheme.", "uri");
        }

        /// <summary>
        /// Determines if the default port is used.
        /// </summary>
        public new bool IsDefaultPort
        {
            get { return base.Port == -1 || base.Port == DefaultPort; }
        }

        /// <summary>
        /// Retrieves the port.
        /// </summary>
        public new int Port
        {
            get { return IsDefaultPort ? DefaultPort : base.Port; }
        }

        /// <summary>
        /// Retrieves the username.
        /// </summary>
        public string Username
        {            
            get { return HttpUtility.UrlDecode(UserInfo).Split(':')[0]; }
        }

        /// <summary>
        /// Retrieves the password.
        /// </summary>
        public string Password
        {
            get { return UserInfo.Contains(":") ? HttpUtility.UrlDecode(UserInfo).Split(':')[1] : string.Empty; }
        }

        /// <summary>
        /// ToString implementation that hides the authentication information.
        /// </summary>
        /// <returns>String URI represenation without authentication information.</returns>
        public override string ToString()
        {           
            return Scheme + SchemeDelimiter + Host + (IsDefaultPort ? string.Empty : ":" + Port);
        }
    }
}